import {
  deleteQuotation,
  exportQuotation,
  getQuotationList,
} from "@/services/quotation";
import {
  DownloadOutlined,
  PlusOutlined,
  SmallDashOutlined,
} from "@ant-design/icons";
import { Card, Button, Tabs, Row, Col, Empty, message } from "antd";
import AddBaojiaDan from "./AddBaojiaDan";
import { useEffect, useRef, useState } from "react";
import { gutter } from "../const/keys";
import PopconfirmButton from "@/components/PopconfirmButton";
import styles from "./index.modules.less";
import { getToken } from "../utils";
import { sleep } from "@/utils";
type Props = {
  id: number;
  data: any;
  isEnd?: boolean;
};

const App = (props: Props) => {
  const { id, isEnd, data } = props;
  const [saveLoading, setSaveLoading] = useState(false);
  const [downloadId, setDownloadId] = useState<number | null>(null);
  const clearRef = useRef<any>(null);
  const [loading, setLoading] = useState(false);
  const [pageNum, setPageNum] = useState(1);
  const [pageSize] = useState(5);
  const [open, setOpen] = useState(false);
  const [isLoadEnd, setIsLoadEnd] = useState(false);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [quantityId, setQuantityId] = useState<number | undefined>();

  const getData = async () => {
    setLoading(true);
    const { data: quotationData } = await getQuotationList({
      businessOpportunityId: id,
      pageNum,
      pageSize,
    });
    if (clearRef.current) {
      setDataSource([...quotationData]);
    } else {
      setDataSource([...dataSource, ...quotationData]);
    }
    setIsLoadEnd(quotationData?.length! < pageSize);
    setLoading(false);
  };
  const donwload = async (id: number, filename = "download.xlsx") => {
    try {
      // message.info("下载功能待开发");
      setSaveLoading(true);
      // const data = await exportQuotation(id);

      const xhr = new XMLHttpRequest();
      xhr.open("POST", `/api/ying/quotation/export/${id}`, true);
      // aplication/json
      xhr.setRequestHeader("Authorization", `Bearer ${getToken()}`);
      xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
      //
      xhr.send(null);
      // xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
      xhr.responseType = "blob";
      xhr.onload = async function () {
        if (this.status === 200) {
          const blob = this.response;
          const downloadUrl = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.href = downloadUrl;
          a.download = filename;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          window.URL.revokeObjectURL(downloadUrl);
          await sleep(2000);
          setSaveLoading(false);
        } else {
          message.error("导出失败");
          setSaveLoading(false);
        }
      };
    } catch (error) {
      setSaveLoading(false);
    }
  };

  const del = async (id: number) => {
    const { success } = await deleteQuotation(id);
    if (!success) {
      return;
    }
    message.success("删除成功");
    clearRef.current = true;
    setPageNum(1);
    setDataSource([]);
    getData();
  };
  useEffect(() => {
    getData();
  }, [pageNum, pageSize]);
  useEffect(() => {
    if (undefined === id) {
      return;
    }
    getData();
  }, [id]);
  return (
    <>
      {open ? (
        <AddBaojiaDan
          readOnly={isEnd}
          businessOpportunityId={id}
          quantityId={quantityId}
          onClose={(reflash) => {
            setOpen(false);
            setQuantityId(undefined);
            if (reflash) {
              clearRef.current = true;
              setPageNum(1);
              setDataSource([]);
              getData();
            }
          }}
        />
      ) : null}
      <Row gutter={[gutter, gutter]}>
        <Col span={24}>
          <Card
            title="相关文档"
            extra={
              isEnd ? null : (
                <Button
                  onClick={() => {
                    setOpen(true);
                  }}
                  icon={<PlusOutlined />}
                  ghost
                  type="primary"
                  size="small"
                >
                  新建报价单
                </Button>
              )
            }
          >
            <Tabs
              items={[
                {
                  label: "报价单",
                  key: "1",
                },
              ]}
            />
            <Row gutter={[gutter, gutter]}>
              {dataSource?.map((item) => {
                return (
                  <Col span={24}>
                    <Card>
                      <Row justify="space-between">
                        <Col span={16}>
                          <Row>
                            <Col
                              span={24}
                              style={{
                                color: "gray",
                              }}
                            >
                              {item.createTime}
                            </Col>
                            <Col
                              span={24}
                              onClick={() => {
                                setQuantityId(item.id);
                                setOpen(true);
                              }}
                            >
                              <strong className={styles.btn}>
                                {item.quotationName}
                              </strong>
                            </Col>
                          </Row>
                        </Col>
                        <Col span={8}>
                          <Row
                            justify="end"
                            onClick={(ev) => {
                              ev.stopPropagation();
                            }}
                          >
                            <Col>
                              <Button
                                type="link"
                                loading={saveLoading && downloadId === item.id}
                                icon={<DownloadOutlined />}
                                onClick={() => {
                                  setDownloadId(item.id);
                                  donwload(item.id, item.quotationName);
                                }}
                              >
                                下载
                              </Button>
                            </Col>
                            <Col>
                              <PopconfirmButton
                                type="link"
                                danger
                                disabled={isEnd}
                                onConfirm={() => {
                                  del(item.id);
                                }}
                              >
                                删除
                              </PopconfirmButton>
                            </Col>
                          </Row>
                        </Col>
                      </Row>
                    </Card>
                  </Col>
                );
              })}

              {dataSource?.length <= 0 ? (
                <Col span={24}>
                  <Row justify="center">
                    <Col>
                      <Empty />
                    </Col>
                  </Row>
                </Col>
              ) : null}
            </Row>
          </Card>
        </Col>

        <Col span={24}>
          <Row justify="center">
            <Col>
              <Button
                size="small"
                type="link"
                loading={loading}
                disabled={isLoadEnd}
                onClick={() => setPageNum(pageNum + 1)}
              >
                加载更多
                <SmallDashOutlined />
              </Button>
            </Col>
          </Row>
        </Col>
      </Row>
    </>
  );
};
export default App;
